package com.hksj.wmp.config;

import com.foxinmy.weixin4j.http.weixin.WeixinRequestExecutor;
import com.foxinmy.weixin4j.mp.token.WeixinTokenCreator;
import com.foxinmy.weixin4j.token.TokenManager;
import com.hksj.common.config.cache.RedisCache;
import com.hksj.wmp.auth.WxPasswordEncoder;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(LoginProperties.class)
public class WxLoginConfig {
    @Value("${hk.wx.appId}")
    private String appId;

    @Value("${hk.wx.appSecret}")
    private String appSecret;

    @Autowired
    private RedisCache accessTokenRedisCache;

    @Bean("wxPasswordEncoder")
    public WxPasswordEncoder wxPasswordEncoder() {
        return (password, salt) -> DigestUtils.md5Hex(String.format("hsweb.%s.framework.%s", password, salt));
    }

    @Bean("weixinRequestExecutor")
    public WeixinRequestExecutor weixinRequestExecutor(){
        return new WeixinRequestExecutor();
    }

    @Bean("accessTokenManager")
    public TokenManager accessTokenManager() {
        WeixinTokenCreator weixinTokenCreator = new WeixinTokenCreator(appId, appSecret);
        RedisCacheStorager redisCacheStorager = new RedisCacheStorager<>(accessTokenRedisCache);
        return new TokenManager(weixinTokenCreator, redisCacheStorager);
    }
}
